package com.example.service.impl;

import com.example.entity.Task;
import com.example.entity.TaskConfig;
import com.example.util.TaskListener;
import com.google.common.util.concurrent.AbstractExecutionThreadService;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.function.Supplier;

/**
 * 任务列表
 *
 * @author wzw
 */
public class MulTaskService extends AbstractExecutionThreadService {

    private Executor executor;

    private List<Task> tasks;

    private List<TaskConfig> taskConfigs;

    private Supplier<TaskListener> taskListenerSupplier;

    public MulTaskService(Executor executor, List<Task> tasks, List<TaskConfig> taskConfigs, Supplier<TaskListener> taskListenerSupplier) {
        this.executor = executor == null ? super.executor() : executor;
        this.tasks = tasks;
        this.taskConfigs = taskConfigs;
        this.taskListenerSupplier = taskListenerSupplier;
    }

    @Override
    protected void run() {
        for (int i = 0; i < tasks.size(); i++) {
            TaskListener taskListener = taskListenerSupplier.get();
            Task task = tasks.get(i);
            TaskConfig taskConfig = taskConfigs.get(i);
            taskListener.setTask(task);
            taskListener.setTaskConfig(taskConfig);
            try {
                taskListener.starting();
                System.out.println(1/0);
                task.execute();
                taskListener.terminated(null);
            } catch (Exception e) {
                taskListener.failed(null, e);
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    protected Executor executor() {
        return executor;
    }
}
